<script setup lang="ts">
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox, ElOption, ElSelect } from 'element-plus'
import Inspecting from './components/Inspecting.vue'
import declartion from './components/declartion.vue'
import { usePage } from '@/utils/commonHook'
import { useDeclareStates, useEnvOrgs, useOwnerOrgs } from '@/utils/dataHook'
import { FilterQuery } from '@/utils/dataHook/data'
import dataQueryApi from '@/api/modules/data.query'
import type { PolluteErrRow } from '@/api/modules/types/data.query'
import { DeviceType } from '@/utils/dataHook/devices'
import useKeepAliveStore from '@/store/modules/keepAlive'
import useUserStore from '@/store/modules/user'
import { statusType } from '@/views/data_query/declare/page'
import { DeclareState } from '@/api/modules/types/data.query'
import { ModelType } from '@/types/common'

defineOptions({
  name: 'DataPolluteErrList',
})
const keepAliveStore = useKeepAliveStore()

onBeforeRouteLeave((to) => {
  if (to.name === 'data-pollute-err-detail') {
    keepAliveStore.add('DataPolluteErrList')
  }
  else {
    keepAliveStore.remove('DataPolluteErrList')
  }
})
const inspectingRef = ref()
const declartionRef = ref()
const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const tableData = ref<any[]>([])
const { page, pageNumChange, pageSizeChange } = usePage(getTableData)

const searchData = reactive(new FilterQuery({
  ObjTypeKey: 'EnvEnterprise',
  Filters: ['DIM.Business.Envs.EnterpriseFilters.EnvOrgGUIDFilter', 'DIM.Units.Filters.NameFilter', 'DIM.Units.Filters.OwnerOrgGUIDFilter'],
}))

interface TimeRangeType {
  startTime: string | null
  endTime: string | null
}

const timeRange = reactive<TimeRangeType>({
  startTime: dayjs().subtract(1, 'day').format('YYYYMMDD'),
  endTime: dayjs().add(1, 'day').format('YYYYMMDD'),
})

const { startTime, endTime } = route.query || {}
if (startTime) {
  timeRange.startTime = startTime as string
}
if (endTime) {
  timeRange.endTime = endTime as string
}

const tiemValue = computed({
  set: (values) => {
    const realValues = values || []
    timeRange.startTime = realValues[0]
    timeRange.endTime = realValues[1]
  },
  get: () => {
    return [timeRange.startTime, timeRange.endTime]
  },
})

const defaultProps = {
  children: 'Children',
  label: 'Name',
}

const OwnerList = userStore.isEnterpris ? [] : useOwnerOrgs()
const envOrgs = userStore.isEnterpris ? [] : useEnvOrgs()
const declareStates = useDeclareStates()

const loading = ref(false)
const declareValue = ref([])
async function getTableData() {
  loading.value = true
  const res = await dataQueryApi.GetReuseExDetails({
    startTime: timeRange.startTime,
    endTime: timeRange.endTime,
    filters: [...searchData.getQuery(),
      {
        ObjTypeKey: 'EnvEnterprise',
        Filter: {
          Type: 'DIM.Business.Envs.ReuseFilters.DeclareStateFilter',
          FilterKey: null,
          Values: declareValue.value,
        },

      } as any,
    ],
    // stateIDs: stateIDs.value,
    pageSize: page.PageSize,
    pageNum: page.PageNum,
  })
  loading.value = false
  // console.log('%c [ res ]-27', 'font-size:13px; background:pink; color:#bf2c9f;', res)
  const { Rows, RecordsetCount } = res
  tableData.value = Rows || []
  page.RecordsetCount = RecordsetCount
}

function search() {
  page.PageNum = 1
  getTableData()
}

getTableData()

function duration(StartTime: string, EndTime: string): string {
  const diffTime = dayjs(EndTime || undefined).diff(
    dayjs(StartTime),
    'm',
  )
  const minute = diffTime % 60
  const hour = Number.parseInt(String(diffTime / 60))
  return `${hour}小时${minute}分钟`
}

function toDetail(row: PolluteErrRow) {
  sessionStorage.setItem('PolluteErrRow', JSON.stringify(row))
  router.push(`/data-query/pollute-err/electric/${row.ProduceObjID}?type=${DeviceType.Produce}&currentTime=${row.StartTime}`)
}

function approve(row: any) {
  inspectingRef.value?.open({
    data: row,
  })
}

function addDeclear(row: any) {
  declartionRef.value?.open({
    type: ModelType.add,
    data: row,
  })
}

function approveSubmit(data: { data: any, isPass: boolean }) {
  const { ProduceObjID, ReusePartObjID, StartTime, inspectContent, inspectName, inspectTel } = data.data
  const formData = {
    produceObjID: ProduceObjID || null,
    reusePartObjID: ReusePartObjID,
    startTime: StartTime,
    inspectContent,
    inspectName,
    inspectTel,
  }

  ElMessageBox.confirm(`确认提交${data.isPass ? '通过' : '驳回'}审核吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const api = data.isPass ? dataQueryApi.ReuseExDeclareEnvOrgPass : dataQueryApi.ReuseExDeclareEnvOrgBack
    api(formData).then(() => {
      ElMessage({
        type: 'success',
        message: '提交成功',
      })
      inspectingRef.value?.close()
      getTableData()
    })
  })
}

function declearSubmit(formData: any) {
  const { ProduceObjID, ReusePartObjID, StartTime, ReportContent, ReportName, ReportTel } = formData
  const data = {
    produceObjID: ProduceObjID || null,
    reusePartObjID: ReusePartObjID,
    startTime: StartTime,
    reportContent: ReportContent,
    reportName: ReportName,
    reportTel: ReportTel,
  }
  dataQueryApi.ReuseExDeclareEnt(data).then((res) => {
    declartionRef.value.upload(res)
    ElMessage({
      type: 'success',
      message: '提交成功',
    })
    declartionRef.value?.close()
    getTableData()
  })
}

function toView(row: any) {
  if (userStore.isEnterpris) {
    declartionRef.value?.open({
      type: ModelType.readonly,
      data: row,
    })
  }
  else {
    inspectingRef.value?.open({
      type: ModelType.readonly,
      data: row,
    })
  }
}
</script>

<template>
  <div>
    <PageHeader>
      <template #content>
        <ElForm label-width="100">
          <ElRow>
            <ElCol v-if="!userStore.isEnterpris" :span="6">
              <ElFormItem label="管理机构">
                <el-tree-select
                  v-model="searchData['DIM.Business.Envs.EnterpriseFilters.EnvOrgGUIDFilter']"
                  value-key="Code" :data="envOrgs" class="w-full" :render-after-expand="false" :props="defaultProps"
                  clearable check-strictly
                />
              </ElFormItem>
            </ElCol>
            <ElCol v-if="!userStore.isEnterpris" :span="6">
              <ElFormItem label="企业名称">
                <ElInput v-model="searchData['DIM.Units.Filters.NameFilter']" clearable placeholder="请输入" />
              </ElFormItem>
            </ElCol>
            <ElCol v-if="!userStore.isEnterpris" :span="6">
              <ElFormItem label="运维公司">
                <el-tree-select
                  v-model="searchData['DIM.Units.Filters.OwnerOrgGUIDFilter']" value-key="Code"
                  :data="OwnerList" check-strictly :render-after-expand="false" :props="defaultProps" clearable
                  class="w-full"
                />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="日期">
                <ElDatePicker v-model="tiemValue" value-format="YYYYMMDD" type="daterange" :clearable="false" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="6">
              <ElFormItem label="申报状态">
                <ElSelect v-model="declareValue" clearable multiple placeholder="请选择申报状态">
                  <ElOption v-for="item in declareStates" :key="item.ID" :label="item.Name" :value="item.ID" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :span="6" :push="userStore.isEnterpris ? 6 : 12" class="flex flex-justify-end">
              <ElButton type="primary" @click="search">
                查询
              </ElButton>
            </ElCol>
          </ElRow>
        </ElForm>
      </template>
    </PageHeader>
    <PageMain>
      <div v-auto-height="85">
        <vxe-table border height="100%" :data="tableData" :loading="loading" :row-config="{ isCurrent: true }">
          <VxeColumn type="seq" title="序号" width="80" />
          <VxeColumn field="EnvOrgName" title="管理机构" min-width="100" show-overflow />
          <VxeColumn field="OwnerOrgName" title="运维公司" min-width="150" show-overflow />
          <VxeColumn field="EntName" title="企业名称" min-width="180" show-overflow />
          <VxeColumn field="ProduceName" title="产污设施" min-width="180" show-overflow>
            <template #default="{ row }">
              <el-button link type="primary" @click="toDetail(row)">
                {{ row.ProduceName }}
              </el-button>
            </template>
          </VxeColumn>
          <VxeColumn field="StartTime" title="异常发生时间" width="200" />
          <VxeColumn field="EndTime" title="异常恢复时间" width="200" />
          <VxeColumn field="ProduceDevNum" title="时长" width="200">
            <template #default="{ row }">
              {{ duration(row.StartTime, row.EndTime) }}
            </template>
          </VxeColumn>
          <VxeColumn field="DeclareStateName" title="申报状态" width="200">
            <template #default="{ row }">
              <el-tag :type="statusType(row.DeclareStateID)">
                {{ row.DeclareStateName }}
              </el-tag>
            </template>
          </VxeColumn>
          <VxeColumn title="操作" width="200">
            <template #default="{ row }">
              <el-button v-if="userStore.isEnterpris && row.DeclareStateID === DeclareState.Declaring" type="primary" link @click="addDeclear(row)">
                申报
              </el-button>
              <el-button v-if="userStore.isEnterpris && row.DeclareStateID === DeclareState.DeclareFail" type="primary" link @click="addDeclear(row)">
                再次申报
              </el-button>
              <el-button v-else-if="userStore.isEnvOrg && row.DeclareStateID === DeclareState.Inspecting" type="primary" link @click="approve(row)">
                审批
              </el-button>
              <el-button v-else type="primary" link @click="toView(row)">
                查看
              </el-button>
            </template>
          </VxeColumn>
        </vxe-table>
      </div>
      <ElPagination
        class="mt-4" :page-size="page.PageSize" :total="page.RecordsetCount" :current-page="page.PageNum"
        layout="total, sizes, prev, pager, next, jumper" :page-sizes="[20, 50, 100]" @current-change="pageNumChange"
        @size-change="pageSizeChange"
      />
      <Inspecting ref="inspectingRef" @submit="approveSubmit" />
      <declartion ref="declartionRef" @submit="declearSubmit" />
    </PageMain>
  </div>
</template>
